package com.wandian.news.mvvm.toutiao.totiaopage;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.mvvm.BaseMVVMFragment;
import com.mylib.libcore.tools.TTAdManagerHolder;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.UIUtils;
import com.qq.e.ads.nativ.express2.NativeExpressAD2;
import com.qq.e.ads.nativ.express2.NativeExpressADData2;
import com.qq.e.ads.nativ.express2.VideoOption2;
import com.qq.e.comm.util.AdError;
import com.wandian.news.adapter.NewsHotRecycleAdapter;
import com.wandian.news.adapter.WXNewsRecycleAdapter;
import com.wandian.news.bean.NewsItemBean;
import com.wandian.news.bean.TouTiaoContentBean;
import com.wandian.news.databinding.NewsFragmentToutiaoChildBinding;
import com.wandian.news.tools.NewsCommonTool;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import static com.mylib.libcore.config.AppConfig.CSJ_ZX_ID;
import static com.mylib.libcore.config.AppConfig.GDT_APP_MB_ZX;

/**
 * @author Administrator
 * @date 2019/12/16-13:30
 * @description 头条-子页面
 **/
public class TouTiaoChildFragment extends BaseMVVMFragment<TouTiaoChildFragmentViewModel> implements BaseQuickAdapter.RequestLoadMoreListener{

    private NewsFragmentToutiaoChildBinding dataBinding;
    private NewsHotRecycleAdapter newsHotRecycleAdapter;
    private TTAdNative mTTAdNative;
    private int page =1;
    private NativeExpressAD2 mNativeExpressAD2;//广点通
    private String title;
    private String value;
    private boolean loadCSJSuccess = false;
    private boolean loadGDTSuccess = false;
    private int sys_width = AppContext.getInstance().getAppPreferenceForever().getAppSysWidth()-20;
    public static TouTiaoChildFragment newInstance(String title) {
        Bundle args = new Bundle();
        args.putString("title", title);
        TouTiaoChildFragment fragment = new TouTiaoChildFragment();
        fragment.setArguments(args);
        return fragment;

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        dataBinding = NewsFragmentToutiaoChildBinding.inflate(inflater);
        dataBinding.setLifecycleOwner(this);
        return dataBinding.getRoot();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        dataBinding.setViewModel(mViewModel);

        title = getArguments().getString("title");
        value = NewsCommonTool.titleToKey(title);
        initRecycleView();
        initViewData();
        initCSJAD();
        initGDTAD();
        getData(true);
    }

    private void initViewData(){
        mViewModel.touTiaoContentBean.observe(this,touTiaoContentBean->{
            if(!UIUtils.isEmpty(touTiaoContentBean) && !UIUtils.isEmpty(touTiaoContentBean.getNewslist())){
                List<NewsItemBean> listNewsData= new ArrayList<>();
                for(TouTiaoContentBean.NewslistBean item:touTiaoContentBean.getNewslist()){
                    NewsItemBean newsItemBean = new NewsItemBean();
                    newsItemBean.setCtime(item.getCtime());
                    newsItemBean.setDescription(item.getDescription());
                    newsItemBean.setPicUrl(item.getPicUrl());
                    newsItemBean.setTitle(item.getTitle());
                    if(listNewsData.size()>0 && listNewsData.size()%3 ==0 ){
                        Random random =new Random();
                        if(random.nextInt(3)==2){
                            newsItemBean.setTypeId(WXNewsRecycleAdapter.AD_PIC);
                        }else {
                            newsItemBean.setTypeId(WXNewsRecycleAdapter.AD_TWO_PIC);
                        }
                    }else {
                        newsItemBean.setTypeId(WXNewsRecycleAdapter.ONE_PIC);
                    }
                    newsItemBean.setUrl(item.getUrl());
                    listNewsData.add(newsItemBean);
                }

                if(mViewModel.isReFlash){
                    newsHotRecycleAdapter.setNewData(listNewsData);
                } else {
                    newsHotRecycleAdapter.addData(listNewsData);
                    newsHotRecycleAdapter.loadMoreComplete();
                }

            }
            if(!UIUtils.isEmpty(dataBinding.srlRefresh)){
                if(dataBinding.srlRefresh.isRefreshing()){
                    dataBinding.srlRefresh.setRefreshing(false);
                }
            }
        });
    }

    /**
     * 初始化穿山甲广告
     */
    private void initCSJAD(){
        try{
            if(mTTAdNative == null){
                TTAdManagerHolder.init(mRootView.getContext());
                mTTAdNative = TTAdManagerHolder.getTTAdNative(mRootView.getContext());
            }
            final AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(CSJ_ZX_ID)
                    .setSupportDeepLink(true)
                    .setExpressViewAcceptedSize(sys_width,90) //期望模板广告view的size,单位dp
                    .setImageAcceptedSize(120, 90)
                    .setAdCount(3)
                    .build();

            //加载广告
            //step5:请求广告，调用feed广告异步请求接口，加载到广告后，拿到广告素材自定义渲染
            //step5:请求广告，对请求回调的广告作渲染处理
            if(!UIUtils.isEmpty(mTTAdNative)){
                mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                    @Override
                    public void onError(int code, String message) {
                        Log.d("loadCSJAdMiddle","message====="+message);
                    }

                    @Override
                    public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                        if (ads == null || ads.isEmpty()) return;
                        if(!UIUtils.isEmpty(newsHotRecycleAdapter)){
                            for(TTNativeExpressAd ad : ads){
                                newsHotRecycleAdapter.getAds().add(ad);
                            }
                            if(!UIUtils.isEmpty(newsHotRecycleAdapter.getData()) && newsHotRecycleAdapter.getData().size()>0 && !loadCSJSuccess){
                                newsHotRecycleAdapter.notifyDataSetChanged();
                                loadCSJSuccess = true;
                            }
                        }
                    }
                });
            }
        }catch (Exception e){

        }
    }

    /**
     * 初始化广点通广告
     */
    private void initGDTAD(){
        try{
            // 创建广告
            Log.d("loadGDTAdMiddle","onLoadSuccess===2==========1111====");
            mNativeExpressAD2 = new NativeExpressAD2(getContext(), GDT_APP_MB_ZX+"",  new NativeExpressAD2.AdLoadListener() {
                @Override
                public void onNoAD(AdError adError) {
                    Log.d("loadGDTAdMiddle","adError====="+ JsonUtil.toJson(adError));
                }

                @Override
                public void onLoadSuccess(List<NativeExpressADData2> list) {
                    if (list == null || list.isEmpty()) {
                        return;
                    }
                    Log.d("loadGDTAdMiddle",sys_width+"sys_widthonLoadSuccess===2=="+list.size());
                    if(!UIUtils.isEmpty(newsHotRecycleAdapter)){
                        for(NativeExpressADData2 ad : list){
                            newsHotRecycleAdapter.getListGDTAD().add(ad);
                        }
                        if(!UIUtils.isEmpty(newsHotRecycleAdapter.getData()) && newsHotRecycleAdapter.getData().size()>0 && !loadGDTSuccess){
                            newsHotRecycleAdapter.notifyDataSetChanged();
                            loadGDTSuccess = true;
                        }
                    }
                }
            });
            mNativeExpressAD2.setAdSize(375, 90); // 单位dp

            VideoOption2.Builder builder = new VideoOption2.Builder();
            /**
             * 如果广告位支持视频广告，强烈建议在调用loadData请求广告前设置setAutoPlayPolicy，有助于提高视频广告的eCPM值 <br/>
             * 如果广告位仅支持图文广告，则无需调用
             */
            builder.setAutoPlayPolicy(VideoOption2.AutoPlayPolicy.WIFI) // WIFI 环境下可以自动播放视频
                    .setAutoPlayMuted(true) // 自动播放时为静音
                    .setDetailPageMuted(false)  // 视频详情页播放时不静音
                    .setMaxVideoDuration(0) // 设置返回视频广告的最大视频时长（闭区间，可单独设置），单位:秒，默认为 0 代表无限制，合法输入为：5<=maxVideoDuration<=61. 此设置会影响广告填充，请谨慎设置
                    .setMinVideoDuration(0); // 设置返回视频广告的最小视频时长（闭区间，可单独设置），单位:秒，默认为 0 代表无限制， 此设置会影响广告填充，请谨慎设置
            mNativeExpressAD2.setVideoOption2(builder.build());
            mNativeExpressAD2.loadAd(5);
        }catch (Exception e){

        }
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {//视图变为可见
        }
    }

    private void initRecycleView(){

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        dataBinding.recyclerChild.setLayoutManager(layoutManager);
        newsHotRecycleAdapter  = new NewsHotRecycleAdapter(new ArrayList<>(),getContext(),value);
        dataBinding.recyclerChild.setAdapter(newsHotRecycleAdapter);
        newsHotRecycleAdapter.setEnableLoadMore(false);
        dataBinding.srlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                newsHotRecycleAdapter.setEnableLoadMore(false);
                getData(true);
            }
        });

        newsHotRecycleAdapter.setOnLoadMoreListener(this, dataBinding.recyclerChild);
    }


    private void getData(boolean isReflsh){
        if(isReflsh){
            page =1;
        }else {
            page++;
            initCSJAD();
            initGDTAD();
        }

        mViewModel.getContentData(value,page,isReflsh,newsHotRecycleAdapter,dataBinding.srlRefresh);
    }

    @Override
    public void onLoadMoreRequested() {
        getData(false);
    }
}
